<template>
  <el-form-item
    class="release-form-item"
    v-if="editorState"
    :label="`${itemName}：`"
    :prop="`${formKey}.${index}.value`"
    :rules="rules">
    <!--下拉框  -->
    <template v-if="itemType === FORM_TYPE_ENUMS.SELECT">
      <el-col :span="editorData.remarks ? 24 : 20">
        <el-select
          :class="{
            'input-block': !editorData.remarks
          }"
          :placeholder="`请选择${itemName}`"
          v-model="editorValue"
          @change="handleSelectChange">
          <el-option v-for="item in listData" :key="item.value" :label="item.name" :value="item" />
        </el-select>
        <span class="form-help" v-if="editorData.remarks" :class="editorData.remarks.length > 24 ? 'blocked': ''">{{editorData.remarks}}</span>
      </el-col>
    </template>
    <!--文本框  -->
    <template v-else-if="itemType === FORM_TYPE_ENUMS.INPUT">
      <el-col :span="editorData.remarks ? 24 : 20">
        <el-input
          :class="{
            'input-block': !editorData.remarks,
            'input-middle': !!editorData.remarks
          }"
          :placeholder="`请输入${itemName}`"
          v-model="editorValue" @change="handleInputChange"/>
        <span class="form-help" v-if="editorData.remarks" :class="editorData.remarks.length > 24 ? 'blocked': ''">{{editorData.remarks}}</span>
      </el-col>
    </template>
    <!--时间段  -->
    <template v-else-if="itemType === FORM_TYPE_ENUMS.TIMES">
      <el-col :span="editorData.remarks ? 24 : 20">
        <el-date-picker
          :class="{
            'input-block': !editorData.remarks
          }"
          v-model="editorValue"
          format="yyyy-MM-dd"
          type="daterange"
          :placeholder="`请选择${itemName}`"
          :picker-options="pickerOptions"
          @change="handleDatesChange"/>
        <span class="form-help" v-if="editorData.remarks" :class="editorData.remarks.length > 24 ? 'blocked': ''">{{editorData.remarks}}</span>
      </el-col>
    </template>
    <!--单个时间  -->
    <template v-else-if="itemType === FORM_TYPE_ENUMS.TIME">
      <el-col  :span="editorData.remarks ? 24 : 20">
        <el-date-picker
          :class="{
            'input-block': !editorData.remarks
          }"
          v-model="editorValue"
          type="date"
          format="yyyy-MM-dd"
          :placeholder="`请选择${itemName}`"
          :picker-options="pickerOptions"
          @change="handleDateChange"/>
        <span class="form-help" v-if="editorData.remarks" :class="editorData.remarks.length > 24 ? 'blocked': ''">{{editorData.remarks}}</span>
      </el-col>
    </template>
    <!--票务 时间区间  -->
    <template v-else-if="itemType === FORM_TYPE_ENUMS.TIME_SECTION">
      <el-col :span="9">
        <el-date-picker
          class="block"
          v-model="editorValue[0]"
          type="datetime"
          format="yyyy-MM-dd HH:mm"
          placeholder="请选择开始时间（必填）"
          :picker-options="pickerOptions"
          @change="handleDateTimeSectionChange(0, $event)"/>
      </el-col>
      <el-col :span="2">
        <div class="date-section">~</div>
      </el-col>
      <el-col :span="9">
        <el-date-picker
          class="block"
          v-model="editorValue[1]"
          type="datetime"
          format="yyyy-MM-dd HH:mm"
          placeholder="请选择结束时间（非必填）"
          :picker-options="pickerOptions"
          @change="handleDateTimeSectionChange(1, $event)"/>
      </el-col>
    </template>
    <!--赛事 活动时间  -->
    <template v-else-if="itemType === FORM_TYPE_ENUMS.M_DATE_TIME">
      <el-col>
        <el-row :gutter="15">
          <el-col :span="10">
            <el-date-picker
              class="block"
              v-model="editorValue.date"
              type="datetime"
              format="yyyy-MM-dd"
              placeholder="请选择日期"
              :picker-options="pickerOptions"
              @change="handleMatchADateChange"/>
          </el-col>
          <el-col :span="10">
            <el-time-picker
              is-range
              v-model="editorValue.time"
              format="HH:mm"
              placeholder="请选择时间范围"
              @change="handleMatchATimeChange"/>
          </el-col>
        </el-row>
      </el-col>
    </template>
    <!-- 课程一开始只有单个地址区多选 改成了下面的方式  后面有需求在启用 -->
    <!-- <template v-else-if="itemType === FORM_TYPE_ENUMS.ADDRESS_SELECTS">
      <cascader-address v-model="editorValue" @change="handleCasAdressChange"/>
    </template> -->
    <!--次课 多地址区多选  -->
    <template v-else-if="itemType === FORM_TYPE_ENUMS.ADDRESS_SELECTS">
      <cascader-address-group v-model="editorValue" @change="handleGroupCasAdressChange"/>
    </template>
    <!-- 单地址 只有赛事有 原有逻辑为省市+详情 v2.4.0 改为省市区+详情 -->
    <template v-else-if="itemType === FORM_TYPE_ENUMS.ADDRESS">
      <el-col>
        <el-row :gutter="15">
          <el-col :span="10">
            <!-- 地址选个更改根据label改变去触发 保证label已更新 -->
            <e-address-cascader class="input-block"
              placeholder="请选择省市区"
              :grade="addressGrade"
              ref="adddressEl"
              v-model="addressHead"
              :label.sync="addressLabel"/>
          </el-col>
          <el-col :span="10">
            <el-input class="input-block"
              placeholder="请输入详细地址"
              v-model.trim="addressDetail"
              @change="handleAddressChange"/>
          </el-col>
        </el-row>
      </el-col>
    </template>
    <!-- 多值文本框 -->
    <template v-else-if="itemType === FORM_TYPE_ENUMS.INPUTS">
      <el-col :span="20">
        <e-input-group :max-item="6" v-model="editorValue" @change="handleInputsChange"/>
      </el-col>
    </template>
    <!-- 单选 -->
    <template v-else-if="itemType === FORM_TYPE_ENUMS.RADIO">
      <el-col :span="24">
        <el-radio-group v-model="editorValue" :disabled="editorDisabed" @change="handleRadioChange">
          <el-radio
            v-for="item in itemData"
            :key="item.value"
            :label="item.name">{{item.name}}
          </el-radio>
        </el-radio-group>
        <span class="form-help" v-if="editorData.remarks" :class="editorData.remarks.length > 24 ? 'blocked': ''">{{editorData.remarks}}</span>
      </el-col>
    </template>
    <!-- 赛事 限制男女单选 -->
    <template v-else-if="itemType === FORM_TYPE_ENUMS.M_NUM_LIMIT">
      <el-col :span="24">
        <el-col :span="3">
          <el-switch
            :width="60"
            v-model="matchLimit"
            on-color="#13ce66"
            off-color="#999"
            on-text="限"
            off-text="不限"
            :disabled="matchLimitDisabled"
            @change="handleMatchLimitChange"/>
        </el-col>
        <el-col :span="5">
          男性最少
          <el-input-number class="input-small xsmall" v-model="editorValue[0]" :no-zero="true" :disabled="!matchLimitState" @change="handleMathLimitNumChange(0, $event)"/>
        </el-col>
        <el-col :span="5">
          女性最少
          <el-input-number class="input-small xsmall" v-model="editorValue[1]" :no-zero="true" :disabled="!matchLimitState" @change="handleMathLimitNumChange(1, $event)"/>
        </el-col>
      </el-col>
    </template>
    <!-- 多选 -->
    <template v-else-if="itemType === FORM_TYPE_ENUMS.CHECKBOX">
      <el-col :span="24">
        <el-checkbox-group v-model="editorValue" @change="handleCheckboxChange">
          <el-checkbox
            v-for="(item) in itemData"
            :label="item"
            :key="item.name">{{item.name}}</el-checkbox>
        </el-checkbox-group>
      </el-col>
    </template>
    <!-- 级联 -->
    <template v-else-if="itemType === FORM_TYPE_ENUMS.CASCADER">
      <el-col :span="20">
        <el-cascader class="input-block"
          :grade="2"
          :props="cascaderProps"
          :options="cascaderList"
          v-model="editorValue"
          @change="handleCasChange"
          @active-item-change="handleCasItemChange"/>
      </el-col>
    </template>
    <!-- 级联 末级多选 -->
    <template v-else-if="itemType === FORM_TYPE_ENUMS.CAS_SELECTS">
      <cascader-selects
        v-model="editorValue"
        :data="data"
        :props="cascaderProps"
        :options="cascaderList"
        @change="handleCasSelectsChange"/>
    </template>
    <!-- 区间 -->
    <template v-else-if="itemType === FORM_TYPE_ENUMS.INPUT_SECTION">
      <e-input-number-range v-model="editorValue" @change="handleSectionChange"/>
      <span class="form-help" v-if="editorData.remarks" :class="editorData.remarks.length > 24 ? 'blocked': ''">{{editorData.remarks}}</span>
    </template>
  </el-form-item>
</template>
<script>
  /**
  * data.type 为定义类型 @param{type 1-下拉框 2-输入框 3-时间 4-地址}
  * data.rules 为验证规则
  * data.name 为字段key
  * data.nameText 为字段文本
  * data.value 为输入值  单选 下拉多选 等需要特殊  如文本框则 值设为 与valueText相等
  * data.valueText 为值文本
  */
  import { mapGetters } from 'vuex'

  // import Group from '@/modules/components/Group'
  import EInputGroup from '@e-ui/InputGroup'
  import EAddressCascader from '@e-ui/AddressCascader'
  import EInputNumberRange from '@e-ui/InputNumberRange'
  import CascaderAddress from './CascaderAddress' // 地址区多选
  import CascaderSelects from './CascaderSelects' // 级联 末级多选
  import CascaderAddressGroup from './CascaderAddressGroup' // 地址区多选
  import serviceApi from 'api/service'
  import { cloneObj } from 'utils'
  import filters from 'src/filters'
  import {
    FORM_TYPE_ENUMS,
    DATA_TYPE_ENUMS,
    CAS_SELECT_TYPE,
    ADDRESS_EMPTY_CODE
  } from '../constant'

  import emitter from 'utils/emitter.js'
  export default {
    mixins: [emitter],
    components: {
      // Group,
      EInputGroup,
      EAddressCascader,
      EInputNumberRange,
      CascaderAddress,
      CascaderSelects,
      CascaderAddressGroup
    },
    props: {
      data: Object,
      formKey: String,
      index: Number,
      basicProps: Array
    },
    computed: {
      ...mapGetters({
        'serviceType': 'service_release_type', // 类目类型 区分 赛事 培训 票务等
        'formItemProp': 'service_release_formitem'
      }),
      itemName () {
        // 字段中文名 标签名
        return this.editorData.attrName
      }
    },
    watch: {
      // 赛事团体 监听每队报名人数 处理限制人数
      'formItemProp.teamMember' (newVal, oldVal) {
        if (this.data.attrCode === 'restrictSex') {
          // 没队报名人数最小值为0 时不可限制
          // 没队报名人数最小值 为 限制人数总和的最12大值
          let maxNum = newVal[0]
          this.resetMatchLimit(maxNum)
        }
      },
      // 赛事团体 监听赛制要求 个人不允许限制男女
      'formItemProp.joinRequire' (newVal, oldVal) {
        if (this.data.attrCode === 'restrictSex') {
          // 个人mathLimitTotalState = true 限制男女不可用
          let isPerson = Boolean((newVal.value - 0) === 20011)
          this.$mathLimitTotalState = isPerson
          this.resetMatchLimit(this.$matchLimitNum || 0)
        }
      },
      editorData () {
        this.$emit('update:data', this.editorData)
      },
      addressLabel (newVl) {
        // 地址updateLbale 后与change事件，所以这里做一下处理
        this.handleAddressChange()
      }
    },
    created () {
      this.initItemData()
      // change at 2017-11-14 v2.2.0
      // 培训课程性质仓库中不能修改
      if (this.serviceType.isTrain && this.serviceType.trainEditState && this.editorData.attrCode === 'properties') {
        this.editorDisabed = true
      }
    },
    data () {
      let {editorData, rules, itemType, editorValue} = this.initBasicData()
      return {
        editorValues: [],
        editorDisabed: !1, // 是否可编辑 默认可以
        editorState: !1, // url模式下 需要获取数据才能编辑
        editorData: editorData,
        editorValue: editorValue,
        // 枚举
        FORM_TYPE_ENUMS,
        CAS_SELECT_TYPE,
        itemData: {},
        itemType: itemType, // 控件类型 1-下拉 2-文本 3-日期 4-地址
        rules: rules, // 验证规则
        // 日期
        pickerOptions: {
          disabledDate (time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        // 地址
        addressGrade: 2, // ADDRESS 地址默认2级 赛事需要改为3级
        addressLabel: '',
        addressHead: [],
        addressDetail: '',
        // 下拉框数据
        listData: [],
        // 区间
        numFrom: 0,
        numTo: 0,
        // 级联数据
        // cascader: [],
        cascaderList: [],
        cascaderState: !0, // 默认第一级有级联 触发二级时再判断
        cascaderProps: {
          label: 'name'
        },
        isFirstLoad: !0, // 是否初始化渲染
        valueToTextObj: {}, // 级联级-对应文本
        matchLimit: true, // 赛事 是否限制男女
        matchLimitDisabled: true, // 是否可限制  默认不可用
        matchLimitState: false // 赛事 限制男女输入状态
      }
    },
    methods: {
      initBasicData () {
        // 由于生命周期  这里不能使用computed中的变量
        // 初始化value  和规则值
        let message = ''
        let editorData = {}
        let editorValue = ''
        let rules = []
        let otherRules = []
        let itemName = this.data.attrName
        let itemType = this.data.showModel - 0
        let isHasChild = Boolean(this.data.children)
        itemType = isHasChild && itemType !== 11 ? FORM_TYPE_ENUMS.CASCADER : itemType // 级联处理
        switch (itemType) {
          case FORM_TYPE_ENUMS.SELECT: // 下拉
            message = `请选择${itemName}`
            editorValue = {}
            break
          case FORM_TYPE_ENUMS.INPUT: // 输入框
            message = `${itemName}不能为空`
            editorValue = ''
            break
          case FORM_TYPE_ENUMS.TIMES: // 时间段
            message = `请选择${itemName}`
            editorValue = []
            break
          case FORM_TYPE_ENUMS.M_DATE_TIME: // 赛事新活动时间
            message = '请选择日期和时间'
            editorValue = {
              date: '',
              time: ''
            }
            break
          case FORM_TYPE_ENUMS.TIME: // 单个时间
            message = `请选择${itemName}`
            editorValue = ''
            break
          case FORM_TYPE_ENUMS.ADDRESS: // 地址
            message = `请选择${itemName}和填写详细地址`
            editorValue = []
            break
          case FORM_TYPE_ENUMS.INPUTS: // 多值输入框
            message = `请输入${itemName}`
            editorValue = []
            break
          case FORM_TYPE_ENUMS.RADIO: // 单选
            message = `请选择${itemName}`
            editorValue = ''
            break
          case FORM_TYPE_ENUMS.M_NUM_LIMIT: // 单选
            message = `请输入${itemName}`
            editorValue = [0, 0]
            let that = this
            otherRules.push({
              validator (rule, value = [], callback) {
                setTimeout(() => {
                  if (value && value.length) {
                    let totalNum = value.reduce((k1, k2) => k1 + k2) || 0
                    if (that.$matchLimitNum < totalNum) {
                      callback(new Error('限制人数之和不能大于每队报名人数的最小值'))
                    }
                  }
                  callback()
                })
              }
            })
            break
          case FORM_TYPE_ENUMS.CHECKBOX: // 多选
            message = `请选择${itemName}`
            editorValue = []
            break
          case FORM_TYPE_ENUMS.CASCADER: // 级联
            message = `请选择${itemName}`
            editorValue = []
            break
          case FORM_TYPE_ENUMS.CAS_SELECTS: // 级联 末级多选
            message = `请选择${itemName}`
            editorValue = []
            break
          case FORM_TYPE_ENUMS.INPUT_SECTION: // 区间
            message = `请输入${itemName}`
            editorValue = [0, 0]
            break
          case FORM_TYPE_ENUMS.TIME_SECTION: // 票务时间区间
            message = `请选择${itemName}`
            editorValue = ['', '']
            break
          // case FORM_TYPE_ENUMS.ADDRESS_SELECTS: // 地址区多选
          //   message = `请选择${itemName}`
          //   editorValue = []
          //   break
          case FORM_TYPE_ENUMS.ADDRESS_SELECTS: // 次课 多地址区多选
            message = `请选择${itemName}`
            editorValue = [[]]
            otherRules.push({
              validator (rule, value = [], callback) {
                setTimeout(() => {
                  let addressArr = value[0] ? JSON.parse(value[0]) : []
                  let tempArr = cloneObj(addressArr)
                  // 如果存在重复项则不给过
                  let isRepeat = addressArr.some((item, iIndex) => {
                    let compareKey = item.distinctId !== ADDRESS_EMPTY_CODE ? 'distinctId' : 'cityId'
                    let exitList = tempArr.filter(k => k[compareKey] === item[compareKey])
                    if (exitList.length > 1) {
                      return true
                    } else {
                      tempArr.shift()
                      return false
                    }
                  })
                  if (isRepeat) {
                    callback(new Error('地址不能重复'))
                  } else {
                    callback()
                  }
                })
              }
            })
            break
        }
        // 初始化规则
        rules.push({
          required: this.data.isRequired,
          // required: !1,
          message: message
        })
        rules = rules.concat(otherRules)
        editorData = Object.assign(this.data, {value: '', valueText: ''})
        return {
          editorData,
          editorValue,
          itemType,
          rules
        }
      },
      initItemData () {
        /**
         * 数据类型 1-url 2-text 3-json
         * 1、一般为下拉框需要通过url获取数据
         * 2、一般为文本框
         * 3、一般为多选框
         */
        let jsonData
        let type = this.editorData.dataType - 0
        let attrValue = this.editorData.attrValue
        // 处理数据 强制将文本类型数据转换
        if (this.itemType === FORM_TYPE_ENUMS.INPUT ||
          this.itemType === FORM_TYPE_ENUMS.TIMES ||
          this.itemType === FORM_TYPE_ENUMS.INPUTS ||
          this.itemType === FORM_TYPE_ENUMS.ADDRESS ||
          this.itemType === FORM_TYPE_ENUMS.INPUT_SECTION ||
          this.itemType === FORM_TYPE_ENUMS.CAS_SELECTS
        ) {
          type = DATA_TYPE_ENUMS.TEXT
        }
        switch (type) {
          case DATA_TYPE_ENUMS.URL:
            // {url, text, value}
            jsonData = JSON.parse(this.editorData.attrValue)
            this.getItemData(jsonData)
            break
          case DATA_TYPE_ENUMS.TEXT:
            this.setTextItemData()
            this.itemData = attrValue
            this.editorState = !0
            break
          case DATA_TYPE_ENUMS.JSON:
            // {data: [], text, value}
            jsonData = JSON.parse(attrValue)
            this.setListItemData(jsonData)
            break
          default:
            this.itemData = attrValue
        }
      },
      getItemData (config) {
        // {url, text, value} URL模式下 约定的格式
        config.url && serviceApi.dict(config.url).then(({data}) => {
          // 请求完成 启用编辑模式
          config.data = data
          this.setListItemData(config)
        })
      },
      setListItemData ({data = [], text, value}) {
        this.editorState = !0
        data = data.map(item => {
          // url模式下 JSON对象的value为数据的value_key
          // url模式下 JSON对象的text为数据的name_key
          item.name = item[text]
          item.value = item[value]
          item.valueObj = { name: item[text], value: item[value] }
          this.valueToTextObj[item.value] = item.name // 第一级
          return {
            ...item,
            children: [] // 级联默认第一级肯定有子集
          }
        })
        let isEditor = this.serviceType.isEditor
        switch (this.itemType) {
          case FORM_TYPE_ENUMS.SELECT:
            this.listData = data
            if (isEditor) {
              let {editorValues, editorTexts} = this.editorData
              let editItem = data.find(k => k.value + '' === editorValues[0] + '')
              this.editorValue = editItem || this.editorValue
              this.setEditorVal(editorValues, editorTexts)
            } else if (!this.editorData.isRequired) {
              this.setEditorVal([])
            }
            break
          case FORM_TYPE_ENUMS.RADIO: // 单选
            this.itemData = data
            let defaultVal = data[0].name
            if (isEditor) {
              let { editorTexts } = this.editorData
              this.editorValue = editorTexts[0] || defaultVal // 编辑状态下针对新增项没有默认值
            } else { // 非编辑默认值
              this.editorValue = defaultVal
            }
            this.handleRadioChange(this.editorValue)
            break
          case FORM_TYPE_ENUMS.CHECKBOX: // 多选
            this.itemData = data
            setTimeout(_ => {
              if (isEditor) {
                let { editorTexts } = this.editorData
                this.editorValue = data.filter(k => editorTexts.includes(k.name))
                this.handleCheckboxChange(this.editorValue)
              }
            }, 200)
            break
          case FORM_TYPE_ENUMS.CASCADER: // 级联
            this.cascaderList = data
            if (isEditor) {
              let {editorValues} = this.editorData
              let curIndex = 0
              let casItem = data.find((k, kIndex) => {
                let flag = Boolean(k.value - 0 === editorValues[0] - 0)
                curIndex = flag ? kIndex : curIndex
                return flag
              })
              this.handleCasItemChange([casItem.value])
            }
            break
        }
      },
      setTextItemData () {
        let isEditor = this.serviceType.isEditor
        switch (this.itemType) {
          case FORM_TYPE_ENUMS.INPUT:
            if (isEditor) {
              let values = this.editorData.editorValues
              this.editorValue = values[0]
              this.setEditorVal(values)
            } else if (!this.editorData.isRequired) {
              this.setEditorVal([])
            }
            break
          case FORM_TYPE_ENUMS.INPUTS:
            if (isEditor) {
              let values = this.editorData.editorValues
              this.editorValue = values
              this.setEditorVal(values)
            } else if (!this.editorData.isRequired) {
              this.setEditorVal([])
            }
            break
          case FORM_TYPE_ENUMS.TIMES:
            if (isEditor) {
              let values = this.editorData.editorValues
              this.editorValue = values
              this.setEditorVal(values)
            } else if (!this.editorData.isRequired) {
              this.setEditorVal([])
            }
            break
          case FORM_TYPE_ENUMS.M_DATE_TIME:
            if (isEditor) {
              let values = this.editorData.editorValues.map(k => new Date(k))
              this.editorValue = {
                date: values[0],
                time: values
              }
              // 上面改值会触发change事件  这里不需要处理
              // this.setEditorVal([values])
            }
            break
          case FORM_TYPE_ENUMS.M_NUM_LIMIT:
            if (isEditor) {
              let values = this.editorData.editorValues
              // let isLimit = values.reduce((k1, k2) => parseInt(k1) + parseInt(k2))
              let teamMemberItem = this.basicProps.find(item => item.attrCode === 'teamMember')
              let joinRequireItem = this.basicProps.find(item => item.attrCode === 'joinRequire')
              let maxNum = teamMemberItem.editorValues[0] - 0
              // 是否为个人
              let isPerson = Boolean(joinRequireItem.editorValues[0] - 0 === 20011)
              this.editorValue = values
              this.matchLimitDisabled = !maxNum
              this.$mathLimitTotalState = isPerson
              this.$matchLimitNum = maxNum // 存取handleMatchLimitChange使用 检验函数
              if (maxNum && !isPerson) {
                this.matchLimit = '0' // 设定为字符0时才能激活
                this.handleMatchLimitChange(this.matchLimit)
              }
            }
            break
          case FORM_TYPE_ENUMS.ADDRESS:
            if (this.serviceType.isMatch) {
              this.addressGrade = 3 // 赛事的时候改为3  票务暂时保持原有的2级
            }
            if (isEditor) {
              let {editorValues, editorTexts} = this.editorData
              // v2.4.0 赛事改为3级 未达到3级的后台会存为空字符串
              let addressHead = editorValues.slice(0, editorValues.length - 1).map(k => k !== '' ? k - 0 : '')
              let addressLabel = editorTexts.slice(0, editorTexts.length - 1) // 转为int类型
              let addressDetail = editorValues.slice(editorValues.length - 1)[0]
              // v2.4.0赛事地址添加区  要对旧数据处理 港澳本来就两级，加区后也无需改变
              // 此规则是强制v2.4.0发布后编辑旧数据如需保存强制让其完善地区
              // [13238, 13257] 港澳地区的首级id
              if (this.serviceType.isMatch) {
                if ([13238, 13257].indexOf(addressHead[0]) !== -1 || addressHead.length === this.addressGrade) {
                  this.addressHead = addressHead
                  this.addressDetail = addressDetail
                  this.addressLabel = addressLabel
                  this.handleAddressChange()
                }
              } else {
                this.addressHead = addressHead
                this.addressDetail = addressDetail
                this.setEditorVal(editorValues, editorTexts)
              }
            }
            break
          case FORM_TYPE_ENUMS.INPUT_SECTION: // 区间
            if (isEditor) {
              /**
               * change detail
               * 新增字段 已有数据编辑数据为空
               * 现处理 当返回数据为空数组时，默认值
               */
              let defaultVal = this.editorValue
              let {editorValues} = this.editorData
              let values = editorValues.length ? editorValues.map(k => k - 0) : defaultVal
              this.editorValue = values
              this.setEditorVal(values)
            } else {
              // 初始化
              this.setEditorVal(this.editorValue)
            }
            break
          // case FORM_TYPE_ENUMS.ADDRESS_SELECTS: // 地址 区多选
          //   if (isEditor) {
          //     let {editorValues, editorTexts} = this.editorData
          //     // 逻辑交由子组件处理
          //     this.editorValue = [editorValues, editorTexts]
          //   } else {
          //     // 初始化
          //     this.setEditorVal(this.editorValue)
          //   }
          //   break
          case FORM_TYPE_ENUMS.ADDRESS_SELECTS: // 次课 地址 区多选
            this.$editorValueText = []
            if (isEditor) {
              let {editorValues, editorTexts} = this.editorData
              let tempValues = JSON.parse(editorValues[0])
              let tempValuesTexts = JSON.parse(editorTexts[0])
              let tempItem = {}
              let curIndex = 0
              tempValues.forEach((item, index) => {
                // ADDRESS_EMPTY_CODE港澳只有两级
                let key = item.distinctId !== ADDRESS_EMPTY_CODE ? `${item.provinceId}_${item.cityId}` : `${item.provinceId}`
                let textItem = tempValuesTexts[index]
                if (tempItem[key]) {
                  tempItem[key].values.push([item, textItem])
                } else {
                  tempItem[key] = {
                    values: [[item, textItem]],
                    index: curIndex
                  }
                  curIndex++
                }
              })
              // 逻辑交由子组件处理
              let resultValues = []
              Object.keys(tempItem).forEach(itemKey => {
                let editItem = tempItem[itemKey]
                let newEditorValues = []
                let newEditorTexts = []
                editItem.values.forEach((k) => {
                  newEditorValues.push(k[0])
                  newEditorTexts.push(k[1])
                })
                resultValues[editItem.index] = [JSON.stringify(newEditorValues), JSON.stringify(newEditorTexts)]
              })
              this.editorValue = resultValues
            } else {
              // 初始化
              this.setEditorVal([])
            }
            break
          case FORM_TYPE_ENUMS.CAS_SELECTS: // 级联 末级多选
            if (isEditor) {
              let {editorValues, editorTexts} = this.editorData
              // 逻辑交由子组件处理
              this.editorValue = [editorValues, editorTexts]
            } else {
              // 初始化
              this.setEditorVal(this.editorValue)
            }
            break
          case FORM_TYPE_ENUMS.TIME_SECTION: // 票务时间区间
            if (isEditor) {
              let {editorValues} = this.editorData
              // 逻辑交由子组件处理
              this.editorValue = editorValues
              this.$dateTimeSction = editorValues
              this.setEditorVal(this.editorValue)
            }
            break
        }
      },
      handleSelectChange (newVal) { // 下拉框处理
        // 下拉框 不会清空数据
        this.setEditorVal([newVal.value + ''], [newVal.name])
        if (this.editorData.attrCode === 'joinRequire' && this.serviceType.isMatchGroupRun) {
          this.$store.commit('SERVICE_RELEASE_INIT_FORMITEM', {
            [this.data.attrCode]: newVal
          })
        }
      },
      handleInputChange (newVal = '') { // 文本框处理
        // 文本框会清空 需要处理变更为''时清空数据setEditorVal
        if (!newVal) {
          this.deleteEditorVal()
          return !1
        }
        this.setEditorVal([newVal.trim()]) // 去前后空格
      },
      handleDatesChange (newVal) { // 时间段框处理
        if (!newVal) {
          this.deleteEditorVal()
          return !1
        }
        let dateArr = newVal.split(' - ')
        this.setEditorVal(dateArr)
      },
      handleDateChange (newVal) { // 单日期框处理
        if (!newVal) {
          this.deleteEditorVal()
          return !1
        }
        this.setEditorVal([newVal])
      },
      handleMatchADateChange (date) {
        let time = this.editorValue.time
        if (date && time) {
          let [startTime, endTime] = this.editorValue.time.map(k => filters.FormatDate(k, 'HH:mm'))
          this.setEditorVal([`${date} ${startTime}`, `${date} ${endTime}`])
        } else {
          this.deleteEditorVal()
        }
      },
      handleMatchATimeChange (time) {
        let date = filters.FormatDate(this.editorValue.date, 'yyyy-MM-dd')
        if (date && time) {
          let [startTime, endTime] = time.split(' - ')
          this.setEditorVal([`${date} ${startTime}`, `${date} ${endTime}`])
        } else {
          this.deleteEditorVal()
        }
      },
      handleDateTimeSectionChange (index, val) {
        // 开始时间必填 结束时间选填
        // dateTimeSction 编辑的时候需要赋值
        this.$dateTimeSction = this.$dateTimeSction || []
        this.$dateTimeSction[index] = val
        this.$dateTimeDefaultMessage = this.$dateTimeDefaultMessage || this.rules[0].message
        /**
         * 1、开始\结束时间都有，则需要结束时间大于开始时间
         * 2、有开始时间 没有结束时间可通过
         */
        let message = this.$dateTimeDefaultMessage + ''
        let isSetVal = (this.$dateTimeSction[0] && this.$dateTimeSction[1] && Date.parse(this.$dateTimeSction[0]) < Date.parse(this.$dateTimeSction[1])) || (this.$dateTimeSction[0] && !this.$dateTimeSction[1])
        if (this.$dateTimeSction[0] && this.$dateTimeSction[1] && Date.parse(this.$dateTimeSction[0]) >= Date.parse(this.$dateTimeSction[1])) {
          message = '结束时间需要大于开始时间'
        } else if (!this.$dateTimeSction[0] && this.$dateTimeSction[1]) {
          message = '请选择开始时间'
        }
        this.rules[0].message = message
        setTimeout(() => {
          if (isSetVal) {
            this.setEditorVal(this.$dateTimeSction)
          } else {
            this.deleteEditorVal()
          }
        }, 10)
      },
      handleAddressChange () { // 地址处理
        if (this.addressHead.length && this.addressDetail) {
          // v2.4.0赛事添加区 地址this.addressHead因为length = 3 港澳为2 需特殊处理 添加空的区级即为第三个位置 ['省', '市', '区']
          // 票务使用的也是这个组件  暂时没有改为三级的需求，需要特殊处理
          // 如果不为三级 且 是赛事发布 则需要添加空项
          let isNeedAddItem = Boolean(this.addressHead.length !== 3 && this.serviceType.isMatch) // 是否不需要添加空项
          let value = isNeedAddItem ? [...this.addressHead, '', this.addressDetail] : [...this.addressHead, this.addressDetail]
          let valueText = isNeedAddItem ? [...this.addressLabel, '', this.addressDetail] : [...this.addressLabel, this.addressDetail]
          this.setEditorVal(value, valueText)
        } else {
          this.deleteEditorVal()
        }
      },
      handleCasAdressChange ({value, valueTexts}) {
        // 地址区多选
        if (value) {
          this.setEditorVal(value, valueTexts)
        } else {
          this.deleteEditorVal()
        }
      },
      handleGroupCasAdressChange ({index, type, value, valueTexts}) {
        if (type === 'update') {
          this.setEditorVal([JSON.stringify(value)], [JSON.stringify(valueTexts)])
        } else if (type === 'delete') {
          this.deleteEditorVal()
        }
      },
      handleRadioChange (newVal) { // 单选框改变处理
        let item = this.itemData.find(item => item.name === newVal)
        this.setEditorVal([item.value], [newVal])
        // 培训课程性质处理
        if (this.data.attrCode === 'properties') {
          this.$store.commit('SERVICE_RELEASE_INIT_FORMITEM', {
            [this.data.attrCode]: newVal
          })
          this.editorData.remarks = {
            '0': '注：专业课，只可设置一门学科和一个教练；',
            '1': '注：综合科，可设置多门学科或多个教练；',
            '2': '注：次课，指按次数销课的课程；'
          }[item.value] || this.editorData.remarks
        }
      },
      resetMatchLimit (maxNum) {
        this.matchLimitDisabled = !maxNum || this.$mathLimitTotalState
        this.$matchLimitNum = maxNum || this.$matchLimitNum // 存取handleMatchLimitChange使用 检验函数
        if (!maxNum || this.$mathLimitTotalState) {
          this.matchLimit = 1
          this.handleMatchLimitChange(this.matchLimit, 'delete') // 加参数强制删除
        } else {
          this.broadcast('ElFormItem', 'el.form.change', this.editorData.value)
        }
      },
      handleMatchLimitChange (newVal, type) { // 赛事限制男女切换
        // newVal 为 string类型
        let state = !(newVal - 0)
        this.matchLimitState = state
        if (!state || type === 'delete') { // 强制删除 或者 关闭时
          this.setEditorVal([0, 0]) // 设定默认值
        } else {
          this.setEditorVal(this.editorValue)
        }
      },
      handleMathLimitNumChange (index, newVal) {
        // 只有两个值 有变化需要修改
        // let otherIndex = index ? index - 1 : index + 1
        // let otherVal = this.editorValue[otherIndex]
        // let curTotalNum = otherVal + newVal
        // if (curTotalNum > this.$matchLimitNum) {
        //   // this.editorValue.splice(index, 1, this.$matchLimitNum - otherVal) // 大于则强制改为0
        // }
        let newArr = [...this.editorValue]
        newArr.splice(index, 1, newVal)
        this.setEditorVal(newArr)
      },
      handleCheckboxChange (newVal = []) { // 多选框改变
        if (newVal.length) {
          let valuesArr = []
          let valueTextsArr = []
          newVal.map(item => {
            valuesArr.push(item.value)
            valueTextsArr.push(item.name)
          })
          this.setEditorVal(valuesArr, valueTextsArr)
        } else {
          this.deleteEditorVal()
        }
      },
      handleInputsChange (newVal) {
        newVal = newVal.filter((k = '') => {
          return k.trim() // 去前后空格
        })
        if (newVal.length) { // 有数据 直接提交
          this.setEditorVal(newVal) // 只传一个 则两个值相同赋值
        } else if (!this.editorData.isRequired) {
          newVal = newVal.length ? newVal : ['']
          this.setEditorVal(newVal)
        } else {
          this.deleteEditorVal()
        }
      },
      handleCasChange (newCasVal) {
        // 级联末级触发时间
        // 初始化
        let value = []
        let valueText = []
        value = newCasVal
        newCasVal.forEach(item => {
          valueText.push(this.valueToTextObj[item])
          // value.push(item.value)
          // valueText.push(item.name)
        })
        this.setEditorVal(value, valueText)
      },
      handleCasSelectsChange (value, valueText) {
        // 级联末级触发时间
        if (value.length) {
          this.setEditorVal(value, valueText)
        } else {
          this.setEditorVal('')
        }
      },
      handleSectionChange (newVal) {
        // 区间
        // 监听变化 用来处理限制男女字段
        if (this.data.attrCode === 'teamMember') {
          this.$store.commit('SERVICE_RELEASE_INIT_FORMITEM', {
            [this.data.attrCode]: newVal
          })
        }
        this.setEditorVal(newVal, newVal)
      },
      setEditorVal (value, valueText) {
        // 统一处理赋值
        this.editorData.value = value
        // 如果valueText 不传 则把value赋值进去
        this.editorData.valueText = valueText || value
        this.broadcast('ElFormItem', 'el.form.change', this.editorData.value)
      },
      deleteEditorVal () {
        this.editorData.value = ''
        this.editorData.valueText = ''
        this.broadcast('ElFormItem', 'el.form.change', [])
      },
      handleCasItemChange (newVal) {
        // 级联中间级点击触发
        let casId = newVal[newVal.length - 1] // 级联id 用于获取数据
        newVal.forEach((k, index) => {
          if (!index) {
            this.curCasData = this.editorData.children
          } else {
            this.curCasData = this.curCasData.children
          }
        })
        let childCasData = this.curCasData.children // 获取子集 如果有子集则添加给下一级 继而下一级到这里时继续判断进行
        let isLastCas = !childCasData // 预算下一级 是否是最后一及
        // 暂时只做URL模式
        let { url, text, value, parentValueType = 0 } = JSON.parse(this.curCasData.attrValue)
        // jsonData 中有一个字段parentValueType
        // 值为1表示所有子集都根据顶级value取获取数据  其他取父级
        // 两级的没有parentValueType字段
        if (parentValueType - 0 === 1) {
          this.casId = newVal[0] // 首级
        } else {
          this.casId = casId // 末级
        }
        url += this.casId
        serviceApi.dict(url).then(({data = []}) => {
          // debugger
          data = data.map(item => {
            item.name = item[text]
            item.value = item[value]
            item.valueObj = { name: item[text], value: item[value] }
            this.valueToTextObj[item.value] = item.name // 子集 暂定由value定 valueText 默认value相同 则valueText相同
            return {
              ...item,
              children: isLastCas ? undefined : [] // 末级则无
            }
          })
          if (newVal.length === 1) {
            let itemIndex = this.cascaderList.findIndex(item => item.value === newVal[0])
            let cascaderItem = Object.assign(this.cascaderList[itemIndex], {
              children: data.length ? data : undefined
            })
            this.$set(this.cascaderList, itemIndex, cascaderItem)
          } else {
            // debugger
            let itemObj = this.cascaderList
            newVal.forEach((item, index) => {
              let itemIndex = itemObj.findIndex(k => k.value === item)
              if (index === 0) {
                itemObj = itemObj[itemIndex].children
              } else if (index < newVal.length - 1) {
                itemObj = itemObj[itemIndex].children
              } else {
                itemObj[itemIndex].children = data.length ? data : undefined
              }
            })
          }
          if (this.serviceType.isEditor && this.isFirstLoad) {
            // 最后一级
            let value = this.curCasData.editorValues ? this.curCasData.editorValues[0] - 0 : data[0].value
            let newSelectValue = [...newVal, value]
            this.editorValue = newSelectValue
            if (!isLastCas) {
              this.handleCasItemChange(newSelectValue)
            } else {
              this.isFirstLoad = !1
              this.handleCasChange(newSelectValue)
            }
          }
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .release-form-item{
    .form-help{
      &.blocked{
        display: block;
        margin-left: 0;
      }
    }
    .date-section{
      font-size: 18px;
      text-align: center;
      line-height: 40px;
    }
    .input-small{
      &.xsmall{
        width: 60px;
      }
    }
  }
</style>

<style lang="scss">
.release-form-item.el-form-item {
  .el-form-item__content {
    .el-input.input-tips{
      width: 290px;
    }
    .el-date-editor.el-input{
      width: 100%;
    }
  }
  .sign_item_btn{
    border-radius: 0;
  }
}
</style>
